package com.tul.exercise.base.thread.synchronize;

/**
 * 非volatile类型变量的自增操作问题
 *
 * @author tuliang
 */
public class VolatileNotAtomic {
    public static volatile long count = 0L;

    public static final int NUMBER = 1000000;

    public static void main(String[] args) {

        // 计数器递减线程
        Thread thread = new SubtractThread();
        thread.start();

        // 计数器递增
        addCount();

        while(thread.isAlive()) {};

        // 多次执行后count基本不为0
        System.out.println("count=" + count);
    }

    /**
     * 计数器递增
     */
    private static void addCount() {
        for (int i = 0; i < NUMBER; i++) {
            count++;
        }
    }

    /**
     * 计数器递减任务线程
     */
    private static class SubtractThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < NUMBER; i++) {
                count--;
            }
        }

    }
}


